import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useThemeStore } from './theme'
import { useAuthStore } from './auth'
import { ElMessage } from 'element-plus'
import api from '@/api'
import CryptoJS from 'crypto-js'

export const useSettingsStore = defineStore('settings', () => {
  const dialogVisible = ref(false)
  const activeMenu = ref('appearance')
  const themeStore = useThemeStore()
  const authStore = useAuthStore()

  // 普通设置
  const settings = ref({
    theme: 'light',
    font: '系统默认字体',
    model: 'deepseek-chat',
    temperature: 0.7
  })

  // 敏感设置 - apiKey会被加密存储
  const sensitiveSettings = ref({
    apiKey: ''
  })

  // 加密函数
  const encryptApiKey = (apiKey) => {
    // 使用固定密钥或从环境变量获取
    const encryptionKey = 'your-secret-encryption-key'
    return CryptoJS.AES.encrypt(apiKey, encryptionKey).toString()
  }

  // 解密函数
  const decryptApiKey = (encryptedApiKey) => {
    const encryptionKey = 'your-secret-encryption-key'
    const bytes = CryptoJS.AES.decrypt(encryptedApiKey, encryptionKey)
    return bytes.toString(CryptoJS.enc.Utf8)
  }

  // 显示设置对话框
  const showSettingDialog = () => {
    if (!authStore.isAuthenticated) {
      ElMessage.error('请先登录')
      return
    }

    // 打开对话框时，同步最新的设置
    settings.value = {
      ...settings.value,
      theme: themeStore.theme || 'dark',
      model: authStore.user?.model || 'deepseek-chat',
      temperature: authStore.user?.temperature || 0.7
    }

    // 从localStorage获取加密的API Key，并尝试解密
    try {
      const encryptedApiKey = localStorage.getItem('encryptedApiKey')
      if (encryptedApiKey) {
        sensitiveSettings.value.apiKey = decryptApiKey(encryptedApiKey)
      }
    } catch (error) {
      console.error('解密API Key失败:', error)
      sensitiveSettings.value.apiKey = ''
    }

    dialogVisible.value = true
  }

  // 关闭设置对话框
  const closeSettingDialog = () => {
    dialogVisible.value = false
  }

  // 保存设置
  const saveSettings = async () => {
    try {
      if (!authStore.isAuthenticated) {
        ElMessage.error('请先登录')
        return
      }

      const settingsToSave = {
        theme: settings.value.theme,
        model: settings.value.model,
        temperature: settings.value.temperature
      }

      // 保存API Key到localStorage（加密存储）
      if (sensitiveSettings.value.apiKey) {
        localStorage.setItem('encryptedApiKey', encryptApiKey(sensitiveSettings.value.apiKey))
      }

      // 使用正确的 API 端点
      const response = await api.put('/user/profile/settings', settingsToSave)

      if (response.data.success) {
        // 更新本地主题
        themeStore.setTheme(settings.value.theme)
        // 更新用户信息
        authStore.updateUserSettings(settingsToSave)

        ElMessage.success('设置保存成功')
        closeSettingDialog()
      } else {
        throw new Error(response.data.message || '保存设置失败')
      }
    } catch (error) {
      console.error('保存设置失败:', error)
      ElMessage.error(error.message || '保存设置失败')
    }
  }

  // 获取API Key（供API请求使用）
  const getApiKey = () => {
    return sensitiveSettings.value.apiKey
  }

  // 切换主题
  const handleThemeChange = () => {
    document.documentElement.setAttribute('data-theme', settings.value.theme)
  }

  // 初始化设置
  const initSettings = () => {
    const currentTheme = themeStore.theme || 'dark'
    settings.value = {
      theme: currentTheme,
      font: '系统默认字体',
      model: 'deepseek-chat',
      temperature: 0.7
    }
    themeStore.setTheme(currentTheme)
  }

  return {
    dialogVisible,
    activeMenu,
    settings,
    sensitiveSettings,
    showSettingDialog,
    closeSettingDialog,
    saveSettings,
    handleThemeChange,
    initSettings,
    getApiKey
  }
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['settings.theme', 'settings.font', 'settings.model', 'settings.temperature'],
        // 确保不保存敏感信息
        excludeKeys: ['sensitiveSettings']
      }
    ]
  }
})
